<?php

namespace shisou\tpinit\lib;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Filesystem;
use think\Image;

class Upload
{
    public function upload($file, $mode, $base64, $thumb = [])
    {
        $domain = '//' . input('server.SERVER_NAME');

        $config = config('upload');

        $publicPath = $config['qiniu']['project'] . '/' . date('Ym') . '/' . date('YmdHis') . rand(10000, 99999);

        $thumbUrl = '';
        $qiniu    = '';
        $local    = '';

        if ($base64) {
            $base64 = base64_decode(str_replace('data:image/jpeg;base64', '', $base64));

            $picName   = $publicPath . '.png';
            $savedFile = public_path() . '/uploads/' . $picName;

            if (!file_exists(dirname($savedFile))) {
                @mkdir(dirname($savedFile), 0777, true);
            }

            file_put_contents($savedFile, $base64);
        } else {
            if (!$file) {
                $json = [
                    'code'    => -1,
                    'data'    => '',
                    'message' => '没有选择上传文件',
                    'success' => false,
                ];

                return json($json);
            }

            try {
                $result = validate(['file' => ['fileSize:10240000,fileExt:gif,jpg,png']])->check(['file' => $file]);

                if ($result) {
                    $picName = Filesystem::disk('public')
                        ->putFile('/', $file, function () use ($file, $publicPath) {
                            return $publicPath;
                        });

                    $savedFile = public_path() . '/uploads/' . $picName;
                }
            } catch (\Throwable $th) {
                $json = [
                    'code'    => -1,
                    'data'    => '',
                    'message' => $th->getMessage(),
                    'success' => false,
                ];

                return json($json);
            }
        }

        if (in_array(1, $mode)) {
            if ($thumb) {
                $thumbName = $publicPath . '_' . $thumb[0] . '×' . $thumb[1] . '.png';
                $image     = Image::open($savedFile);
                $image->thumb($thumb[0], $thumb[1])
                    ->save(public_path() . '/uploads/' . $thumbName);

                $thumbUrl = '/uploads/' . $thumbName;
            }

            $local = [
                'url'     => '/uploads/' . '/' . $picName,
                'fullurl' => $domain . '/uploads/' . '/' . $picName,
                'thumb'   => $thumbUrl,
            ];
        }

        if (in_array(2, $mode)) {
            $token = (new Auth($config['qiniu']['accessKey'], $config['qiniu']['secretKey']))->uploadToken($config['qiniu']['bucket']);

            $info = (new UploadManager())->putFile($token, $picName, $savedFile);

            if ($thumb) {
                $format   = '?imageView2/1/w/' . $thumb[0] . '/h/' . $thumb[1] . '/q/75';
                $thumbUrl = '/' . $info[0]['key'] . $format;
            }

            if (!in_array(1, $mode)) {
                unlink($savedFile);
            }

            $qiniu = [
                'url'     => '/' . $info[0]['key'],
                'fullurl' => $config['qiniu']['domain'] . '/' . $info[0]['key'],
                'thumb'   => $thumbUrl,
            ];
        }

        return [
            'local' => $local,
            'qiniu' => $qiniu,
        ];
    }
}